<template>
  <div class="send-circle">
    <div class="circle-content">
      <h3>朋友圈内容</h3>
      <div class="set-content scroll">
        <!-- 选择朋友圈类型 -->
        <div class="send-circle-item">
          <p class="circle-item-tip">类型</p>
          <el-radio-group v-model="circleType">
            <el-radio label="text">文本</el-radio>
            <el-radio label="picture">图文</el-radio>
            <el-radio label="video">视频</el-radio>
            <el-radio label="link">链接</el-radio>
          </el-radio-group>
        </div>

        <!-- 设置文字 -->
        <div class="send-circle-item">
          <p class="circle-item-tip">文字</p>
          <el-input v-model="textContent" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" maxlength="500"
            show-word-limit placeholder="请输入内容"></el-input>
        </div>

        <!-- 选择媒体 -->
        <div v-if="circleType === 'picture' || circleType === 'video'" class="send-circle-item">
          <p class="circle-item-tip">媒体</p>

          <div v-if="circleType === 'picture'" class="media-list">
            <div v-for="(imgItem, index) in imagesList" :key="index" class="img-item" draggable="true"
              @dragover="imgDragOver($event, index)" @dragend="imgDragEnd($event, index)">
              <img class="img-url" :src="imgItem" alt="图片miss" />
              <div class="img-delete">
                <i class="el-icon-circle-plus-outline" style="margin-right: 5px" @click="showBigImg(imgItem)"></i>
                <i class="el-icon-delete" @click="removeImg(index)"></i>
              </div>
            </div>

            <div v-if="imagesList.length < 9">
              <label class="upload-box" for="fileInput">
                <i class="el-icon-plus"></i>
              </label>
              <input v-show="false" id="fileInput" ref="sendCircleUpload" type="file"
                :accept="circleType === 'picture' ? '.jpg, .png, .jpeg' : '.mp4'"
                :multiple="circleType === 'picture' ? true : false" @change="choseMedia()" />
            </div>
          </div>

          <div v-else class="media-list">
            <video v-if="videoList.length > 0" style="max-width: 300px" :src="videoList[0]" width="100%"
              controls></video>

            <div v-if="videoList.length === 0">
              <label class="upload-box" for="fileInput">
                <i class="el-icon-plus"></i>
              </label>
              <input v-show="false" id="fileInput" ref="sendCircleUpload" type="file"
                :accept="circleType === 'picture' ? '.jpg, .png, .jpeg' : '.mp4'"
                :multiple="circleType === 'picture' ? true : false" @change="choseMedia()" />
            </div>
            <el-button v-else style="height: 40px; align-self: center; margin-left: 20px" class="el-icon-delete"
              type="primary" @click="videoList = []">
              删除视频
            </el-button>
          </div>
        </div>

        <!-- 设置连接内容 -->
        <div v-if="circleType === 'link'" class="send-circle-item">
          <p class="circle-item-tip">链接</p>
          <div class="link-content">
            <div class="link-content-item">
              <!-- 链接的title -->
              <el-input v-model="linkTitle" style="margin-bottom: 10px" type="textarea" placeholder="请输入链接标题"
                maxlength="200" show-word-limit :autosize="{ minRows: 6, maxRows: 6 }" resize="none"></el-input>
              <!-- 图片的url -->
              <el-input v-model="linkImg" style="margin-bottom: 10px" placeholder="请输入图片地址" maxlength="200"
                minlength="12" clearable></el-input>
              <!-- 链接的url -->
              <el-input v-model="linkUrl" placeholder="请输入链接地址" maxlength="200" minlength="12" clearable></el-input>
            </div>
            <div class="link-content-item">
              <p style="padding: 0 0 10px 0">预览</p>
              <div class="preview-box">
                <img style="width: 100px; margin-right: 10px" :src="linkImg" alt="" />
                <p class="link-title" v-text="linkTitle"></p>
              </div>
            </div>
          </div>
        </div>

        <!-- 设置发送时间 -->
        <div class="send-circle-item">
          <p class="circle-item-tip">发送方式</p>
          <div class="sent-time-content">
            <el-radio-group v-model="sendRadio">
              <el-radio :label="'rightNow'">立即发送</el-radio>
              <el-radio :label="'timingTask'">定时发布</el-radio>
              <el-radio :label="'periodTask'">周期发布</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div v-if="sendRadio === 'rightNow'" class="send-circle-item">
          <span class="tip" style="margin-left: 20px">间隔(分)</span>
          <el-input-number v-model="breakTime" size="small" controls-position="right" :min="0" :max="30"
            style="margin: 0 5px; width: 80px"></el-input-number>
        </div>

        <div v-if="sendRadio === 'timingTask'" class="send-circle-item">
          <p class="circle-item-tip">选择时间</p>
          <el-date-picker v-model="refTime" style="width: 190px;" type="datetime" placeholder="选择日期时间" @change="getEndTime"
            prefix-icon="el-icon-date" clearable size="small"></el-date-picker>

          <span class="tip" style="margin-left: 20px">间隔(分)</span>
          <el-input-number v-model="breakTime" size="small" controls-position="right" :min="0" :max="30"  @change="getEndTime"
            style="margin: 0 5px; width: 80px"></el-input-number>
        </div>

        <div v-if="sendRadio === 'periodTask'" class="sent-time-content">
          <div class="send-circle-time">
            <p style="padding: 0 10px 0 10px">任务描述</p>
            <el-input v-model.trim="taskName" style="width: 300px; margin-left: 10px" placeholder="任务描述" size="small"
              clearable maxlength="20" show-word-limit></el-input>
          </div>
          <div class="send-circle-time">
            <p style="padding: 0 20px 0 10px">周期</p>
            <el-radio-group v-model="periodType"   @change="getEndTime">
              <el-radio :label="'everyDay'">每天</el-radio>
              <el-radio :label="'twoDays'">隔天</el-radio>
            </el-radio-group>
          </div>
          <div class="send-circle-time">
            <p style="padding: 0 10px 0 10px">选择时间</p>
            <el-time-picker v-model="refTime" style="width: 190px; "   @change="getEndTime" :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }" type="datetime" placeholder="选择时间" prefix-icon="el-icon-date" clearable size="small"></el-time-picker>
            <span class="tip" style="padding: 0 10px 0 20px">间隔(分)</span>
            <el-input-number v-model="breakTime" size="small" controls-position="right" :min="0" :max="30"   @change="getEndTime"
              style="margin: 0 5px; width: 80px"></el-input-number>
          </div>
          <div class="send-circle-time">
            <p style="padding: 0 10px 0 10px">时间范围</p>
            <el-date-picker v-model="timeRange" style="width: 350px; " size="small" type="daterange" range-separator="至"   @change="getEndTime"
              start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>

          </div>
        </div>
        <div class="send-circle-item" v-if="circle2sendInfo">
          <p class="circle-item-tip">来源用户</p>
          <div class="sent-time-content">
            {{ circle2sendInfo.FriendNick }}
          </div>
        </div>
        <div class="send-circle-item">
          <p class="circle-item-tip">发送类型</p>
          <div class="sent-time-content">
            <el-radio-group v-model="send_type">
              <el-radio :label="0">主动发送</el-radio>
              <el-radio :label="1">被动发送</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="send-circle-item">
          <p class="circle-item-tip" style="width: 80px;">朋友圈类型</p>
          <div class="sent-time-content">
            <el-radio-group v-model="circle_type" :disabled="editMode">
              <el-radio label="普通">普通</el-radio>
              <el-radio label="广告">广告</el-radio>
              <el-radio label="续费客户">续费客户</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div style="padding-right: 10px;">
          <div v-if="circle_type == '广告' || circle_type == '续费客户'" style="border: 1px dashed #ccc; width: 100%;">
            <div class="send-circle-item">
              <p class="circle-item-tip" style="width: 80px;">收款金额</p>
              <div class="sent-time-content">
                <!--只能是数字，保留两位小数 value.replace(/[^\-?\d.]/g,'')"-->
                <el-input v-model="price_num" @input="handleInput" placeholder="请输入" :disabled="editMode" />
                <span style="margin-left: 10px;">元</span>
              </div>
            </div>
            <div class="send-circle-item">
              <p class="circle-item-tip" style="width: 80px;">收款截图</p>
              <div class="sent-time-content">
                <div class="media-list">
                  <div v-for="(imgItem, index) in priceImagesList" :key="index" class="img-item" draggable="true"
                    @dragover="imgDragOver($event, index)" @dragend="imgDragEnd($event, index)">
                    <img class="img-url" :src="imgItem" alt="图片miss" />
                    <div class="img-delete">
                      <i class="el-icon-circle-plus-outline" style="margin-right: 5px" @click="showBigImg(imgItem)"></i>
                      <i class="el-icon-delete" @click="removeImg2(index)" v-if="!editMode"></i>
                    </div>
                  </div>

                  <div v-if="priceImagesList.length < 9 && !editMode">
                    <label class="upload-box" for="fileInput2">
                      <i class="el-icon-plus"></i>
                    </label>
                    <input v-show="false" id="fileInput2" ref="sendCircleUpload2" type="file"
                      :accept="'.jpg, .png, .jpeg'"
                      :multiple="true " @change="choseMedia2()" />
                  </div>
                </div>
              </div>
            </div>
            <div class="send-circle-item">
              <p class="circle-item-tip" style="width: 80px;">到期时间</p>
              <div class="sent-time-content" style="flex-direction: column">
                <!-- <div class="btns">
                  <button @click="endTimeOut(1)">一天后</button>
                  <button @click="endTimeOut(3)">三天后</button>
                  <button @click="endTimeOut(7)">一周后</button>
                  <button @click="endTimeOut(30)">三十天后</button>
                </div>
                <div class="date-picker-container">
                  <el-date-picker v-model="end_time" style="width: 270px;" type="datetime" placeholder="选择日期时间"
                    prefix-icon="el-icon-date" clearable size="small">
                  </el-date-picker>
                </div> -->
                <div>
                  {{ formattedDateTime(end_time) }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 设置评论 -->
        <div class="send-circle-item">
          <p class="circle-item-tip">评论</p>
          <el-input v-model="commentContent" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" maxlength="500"
            show-word-limit placeholder="请输入内容"></el-input>
        </div>
      </div>

      <!-- 创建任务 -->
      <div class="create-btn">
        <el-button :loading="createLoading" type="primary" icon="el-icon-position" @click="createSendTask">
          提 交
        </el-button>
      </div>
    </div>

    <!-- 预览大图 -->
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <div class="chose-wechat">
      <h3>选择个人号</h3>
      <div class="chose-wechat-item">
        <el-select v-model="wechatsGroup2Send" style="width: 100%" multiple filterable clearable placeholder="请选择"
          @change="groupChangeHandle" @remove-tag="removeGroup">
          <el-option v-for="item in groupsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </div>

      <div class="wechats-list">
        <!-- 账号列表 -->
        <div class="wechats-unchose">
          <div class="wechats-unchose-title">
            <el-checkbox v-model="allChoseRadio" @change="choseAllWechats">{{ wechatsUnchose.length }} 项</el-checkbox>
            <span>账号列表</span>
          </div>
          <ul class="wechats-unchose-list">
            <li v-for="(wechat, index) in wechatsUnchose" :key="index" class="wechats-unchose-item">
              <input type="checkbox" name="vehicle" :value="wechat.wechatid" :checked="wechatsChoseMap[wechat.wechatid]"
                @change="choseWechat(wechat)" />
              <div style="margin-left: 20px" v-text="wechat.wechatnick"></div>
            </li>
          </ul>
        </div>

        <!-- 转移按钮 -->
        <div class="chose-wechat-btns">
          <el-button icon="el-icon-arrow-right" @click="add2Send"></el-button>
          <el-button style="margin: 0" icon="el-icon-arrow-left" @click="remove2send"></el-button>
        </div>

        <!-- 已选账号 -->
        <div class="wechats-unchose">
          <div class="wechats-unchose-title">
            <el-checkbox v-model="allChoseRadio2" @change="choseAllWechats2">{{ wechats2send.length }} 项</el-checkbox>
            <span>已选账号</span>
          </div>
          <ul class="wechats-unchose-list">
            <li v-for="(wechat, index) in wechats2send" :key="index" class="wechats-unchose-item">
              <input type="checkbox" name="vehicle" :value="wechat.wechatid"
                :checked="wechatsChoseMap2[wechat.wechatid]" @change="choseWechat2(wechat)" />
              <div style="margin-left: 20px" v-text="wechat.wechatnick"></div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { uniqueArryList } from '@/utils/util'
import { fileUpload } from '@/utils/upload'

import { mapGetters } from 'vuex'
import { getAllDeviceGroup } from '@/api/admin/group'
import { getAllDevices } from '@/api/admin/device'
import { addCircle, editCircle, deleteCircleTask } from '@/api/front/circle'

export default {
  name: 'SendCircle',
  data() {
    return {
      tid: 0, // 任务id
      circleType: 'picture', // 朋友圈类型
      textContent: '', // 文本内容
      commentContent: '', // 评论内容
      sendRadio: 'rightNow', // 立即发送还是定时发送
      periodType: 'everyDay', // 周期类型
      refTime: new Date().getTime(), // 定时发送的时间
      timeRange: [], // 周期时间范围
      taskName: '', // 周期任务名称
      createLoading: false,
      breakTime: 0, // 定时发送的间隔时间

      imgTarget: null,
      imagesList: [], // 图片回显列表
      videoList: [], // 视频回显列表
      dialogVisible: false, // 预览媒体
      dialogImageUrl: '', // 要预览的媒体url
      linkTitle: '', // 链接标题
      linkUrl: '', // 链接地址
      linkImg: '', // 链接图片

      groupsList: [], // 账号分组列表
      wechatsGroup2Send: [], // 选择的分组

      wechatsList: [], // 账号列表
      wechatsUnchose: [],
      wechatsChose: [], // 预选的未选中的账号
      wechatsChose2: [], // 预选的选中的账号
      wechats2send: [], // 已选账号
      allChoseRadio: false,
      allChoseRadio2: false,
      circle2sendInfo: null,
      send_type: 0,
      circle_type: "普通",
      price_num: 0,
      price_url: '',
      end_time: new Date(),
      priceImagesList: [],

    }
  },
  watch: {
    sendRadio(e) {
      console.log(e);
      this.getEndTime();
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      circleData: 'circleManager/circleData',
      circle2send: 'circleManager/circle2send',
      editMode: 'circleManager/editMode'
    }),
    wechatsChoseMap() {
      const wsm = {}
      for (const wcc of this.wechatsChose) {
        wsm[wcc.wechatid] = true
      }
      return wsm
    },
    wechatsChoseMap2() {
      const wsm = {}
      for (const wcc of this.wechatsChose2) {
        wsm[wcc.wechatid] = true
      }
      return wsm
    }
  },
  created() {
    let resendWechats = []
    console.log(JSON.stringify(this.circleData));
    if (JSON.stringify(this.circleData) !== '{}') {
      const { wechats, remarks } = this.circleData
      resendWechats = wechats
      try {
        const { textContent, circleType, attachtContent, groups, videoList, imagesList, comment } = JSON.parse(remarks)
        this.textContent = textContent
        this.commentContent = comment == undefined ? '' : comment
        this.circleType = circleType
        let AttachContent = []
        if (attachtContent) {
          AttachContent = attachtContent.split(',')
        }
        if (circleType === 'picture') {
          this.imagesList = JSON.parse(imagesList)
        } else if (circleType === 'video') {
          this.videoList = JSON.parse(videoList)
        } else {
          // 链接
          this.linkUrl = AttachContent[0]
          this.linkTitle = AttachContent[1]
          this.linkImg = AttachContent[2]
        }
        if (groups) {
          this.wechatsGroup2Send = groups.split(',')
        }
      } catch (error) {
        console.log(error)
      }

      if (this.editMode) {
        console.log('编辑模式');
        console.log(this.circleData);
        const { 
          id, task_name, cycle_type, execute_time, end_time, between_time, price_num, price_url, price_end_time,
          send_type,circle_type
         } = this.circleData
        console.log('cycle_type %d between %d', cycle_type, between_time);
        this.price_num = price_num
        this.price_url = price_url
        this.price_end_time = new Date(price_end_time)
        this.price_end_time_str = this.formattedDateTime(this.price_end_time)
        this.circle_type = circle_type
        this.priceImagesList = JSON.parse(price_url)

        this.tid = id
        this.taskName = task_name
        const cycleType = (typeof cycle_type === 'number' && !Number.isNaN(cycle_type)) ? cycle_type : 0;
        this.periodType = cycleType === 2 ? 'twoDays' : 'everyDay'
        this.sendRadio = cycleType === 0 ? 'timingTask' : 'periodTask'
        console.log('ref %s end %s', execute_time, end_time);
        this.refTime = new Date(execute_time)
        if (this.sendRadio === 'periodTask') {
          // 周期任务
          this.timeRange = [new Date(execute_time), new Date(end_time)]
        } else {
          // 定时任务
          this.timeRange = []
        }
        this.breakTime = (typeof between_time === 'number' && !Number.isNaN(between_time)) ? between_time : 5;
      }
    }else{
      this.editMode = false
    }
    // 处理待发送的朋友圈
    if (JSON.stringify(this.circle2send) !== '{}') {
      this.circle2sendInfo = this.circle2send;
      const { textContent, media } = this.circle2send
      this.textContent = textContent
      if (media) {
        this.circleType = 'picture'
        this.imagesList = media
      } else {
        this.circleType = 'text'
      }
    }
    // 获取所有的分组
    getAllDeviceGroup(this.currentUser.SupplierId).then((res) => {
      this.groupsList = res.data || []
    })
    // 获取所有的设备
    getAllDevices(this.currentUser.SupplierId, this.currentUser.UnionId).then((res) => {
      this.wechatsList = res.data || []
      this.wechatsUnchose = this.wechatsList.filter((x) => {
        return resendWechats.indexOf(x.wechatid) < 0
      })
      this.wechats2send = this.wechatsList.filter((x) => {
        return resendWechats.indexOf(x.wechatid) >= 0
      })
    })
  },
  beforeDestroy() {
    this.$store.commit('circleManager/SET_CIRCLE_DATA', {})
    this.$store.commit('circleManager/SET_CIRCLE_2_SEND', {})
  },
  methods: {
    getEndTime(){
      if(this.sendRadio=='rightNow'){
        this.end_time=new Date();
      }else if(this.sendRadio=='timingTask'){
        this.end_time=new Date(this.refTime+(this.breakTime*60*1000));
      }else if(this.sendRadio=='periodTask'){
        //获取时分秒
        let time = new Date(this.refTime);
        if(!time || !this.timeRange[1]){
          this.end_time=null;
          return;
        }
        let sfm = time.getHours() * 60 * 60 * 1000 + time.getMinutes() * 60 * 1000 + time.getSeconds() * 1000;
        console.log(this.timeRange[1],sfm,(this.breakTime*60*1000))
        let day=0;
        if(this.periodType==='twoDays'){
          day=1;
        }
        this.end_time=new Date(this.timeRange[1].getTime()+sfm+(this.breakTime*60*1000)+day*24*60*60*1000);
      }
    },
    formattedDateTime(date) {
      if(!date){
        return '';
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    endTimeOut(num) {
      this.end_time = new Date();
      this.end_time.setDate(this.end_time.getDate() + num);
    },
    handleInput(e) {
      // 过滤非数字、小数点、负号字符
      let val = this.price_num.replace(/[^0-9.-]/g, '');

      // 处理多个负号（只保留第一个）
      val = val.replace(/-+/g, '-').replace('--', '-');

      // 限制负号只能在开头
      if (val.indexOf('-') > 0) val = val.replace(/-/g, '');

      // 限制小数点后最多两位
      if (val.includes('.')) {
        const [integer, decimal] = val.split('.');
        val = `${integer}.${decimal.slice(0, 2)}`;
      }

      // 空字符串或纯负号时置空
      if (val === '-' || !val) val = '';

      this.price_num = val;
    },
    // 定时群发 时间转换
    transformTime(times) {
      const date = new Date(times)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      const time = Y + M + D + h + m
      return time
    },
    // 周期发送时间
    transformTime2(sdate, times) {
      const date = new Date(sdate)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const time = new Date(times)
      const h = (time.getHours() < 10 ? '0' + time.getHours() : time.getHours()) + ':'
      const m = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
      const timeStr = Y + M + D + h + m
      return timeStr
    },
    // 创建朋友圈任务
    createSendTask() {
      // 表单验证
      if (this.circleType === 'text' && !this.textContent) {
        this.$message.warning('请设置文本内容!')
        return
      } else if (this.circleType === 'picture' && this.imagesList.length === 0) {
        this.$message.warning('请设置图片!')
        return
      } else if (this.circleType === 'video' && this.videoList.length === 0) {
        this.$message.warning('请设置视频!')
        return
      } else if (this.circleType === 'link' && (!this.linkUrl || !this.linkImg || !this.linkTitle)) {
        this.$message.warning('请设置链接参数!')
        return
      }
      // 附件
      let attachment = {}
      switch (this.circleType) {
        case 'picture':
          attachment = {
            Type: 2,
            Content: this.imagesList
          }
          break
        case 'video':
          attachment = {
            Type: 3,
            Content: this.videoList
          }
          break
        case 'link':
          // 链接：[url;标题;图片url]
          attachment = { Type: 0, Content: [this.linkUrl, this.linkTitle, this.linkImg] }
          break
        default:
          break
      }

      // 指定微信
      if (this.wechats2send.length === 0) {
        this.$message.warning('请选择微信!')
        return
      }

      if (this.sendRadio === 'periodTask' && this.timeRange.length === 0) {
        this.$message.warning('请选择周期时间!')
        return
      }

      let tipMsg = '即将发送朋友圈, 是否继续?'
      if (this.editMode) {
        tipMsg = '即将修改朋友圈任务, 是否继续?'
      }
      // 二次确认
      this.$confirm(tipMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const { SupplierId, UnionId } = this.currentUser
          let execute_time // 执行时间
          let end_time = '' // 结束时间
          let cycle_type = 0 // 周期类型
          // 立即发送还是定时发送
          if (this.sendRadio === 'rightNow') {
            execute_time = this.transformTime(new Date().getTime() + 60 * 1000)
          } else if (this.sendRadio === 'timingTask') {
            execute_time = this.transformTime(this.refTime)
          } else if (this.sendRadio === 'periodTask') {
            // 周期任务
            execute_time = this.transformTime2(this.timeRange[0], this.refTime)
            end_time = this.transformTime2(this.timeRange[1], this.refTime)
            cycle_type = this.periodType === 'everyDay' ? 1 : 2
          }
          let wechats = this.wechats2send.map((x) => {
            return x.wechatid
          })
          // wechats去重
          wechats = uniqueArryList(wechats)
          let restype = ''
          let attachtype = ''
          let attachtcontent = ''

          const remarks = {
            textContent: this.textContent,
            circleType: this.circleType,
            groups: this.wechatsGroup2Send.join(','),
            comment: this.commentContent
          }

          if (this.circleType !== 'text') {
            restype = attachment.Type // 附件类型
            attachtype = attachment.Type // 附件类型
            attachtcontent = attachment.Content.join(',') // 附件内容
            remarks.attachtContent = attachment.Content.join(',')
          }

          if (this.circleType === 'picture') {
            remarks.imagesList = JSON.stringify(this.imagesList)
          } else if (this.circleType === 'video') {
            remarks.videoList = JSON.stringify(this.videoList)
          }

          

          let data = {
              cid: SupplierId,
              accountid: UnionId,
              execute_time: execute_time,
              restype: restype,
              content: this.textContent,
              wechats: wechats.join(','),
              comment: this.commentContent,
              attachtype: attachtype,
              attachtcontent: attachtcontent,
              between_time: this.breakTime,
              remarks: JSON.stringify(remarks),
              cycle_type: cycle_type,
              end_time: end_time,
              task_name: this.taskName,
              send_type: this.send_type,
              circle_type: this.circle_type,
            };
            if (this.circle2sendInfo) {
              data.origin_wechatid = this.circle2sendInfo.WeChatId
              data.origin_friendid = this.circle2sendInfo.FriendId
              data.origin_name = this.circle2sendInfo.FriendNick
              data.origin_avatar = this.circle2sendInfo.Avatar
            }
            if (this.circle_type=='广告'||
              this.circle_type=='续费客户') {
              data.price_num = this.price_num
              data.price_url =  JSON.stringify(this.priceImagesList)
              //时间转 yyy-mm-dd xx:xx:xx
              data.price_end_time_str = this.formattedDateTime(this.end_time);
            }
          if (this.editMode) {
            data.id=this.tid;
            editCircle(data)
              .then((res) => {
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '任务修改成功!',
                    duration: 2000
                  })

                  // 跳转到朋友圈列表页面
                  this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'allCircle')
                  this.$store.commit('circleManager/SET_CIRCLE_DATA', {})
                  this.$store.commit('circleManager/SET_EDIT_MODE', false)
                }
              })
              .catch((err) => {
                this.$message({
                  type: 'error',
                  message: `任务修改失败${err}`,
                  duration: 2000
                })
              })
          } else {
            addCircle(data)
              .then((res) => {
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '任务创建成功!',
                    duration: 2000
                  })

                  // 跳转到朋友圈列表页面
                  // this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'allCircle')
                  // 跳转到聊天页面
                  this.$router.replace({ name: 'conversation' })

                  if (this.circle2send.id) {
                    // 删除待发任务
                    this.$store.commit('circleManager/DELETE_CHAT_LIST_BY_ID', this.circle2send.id)
                    // 重置待发数据
                    this.$store.commit('circleManager/SET_CIRCLE_2_SEND', {})
                  }

                  // 如果是重发 删除原来的任务
                  if (JSON.stringify(this.circleData) !== '{}') {
                    deleteCircleTask(this.circleData.id).then(() => {
                      this.$store.commit('circleManager/SET_CIRCLE_DATA', {})
                    })
                  }
                }
              })
              .catch((err) => {
                this.$message({
                  type: 'error',
                  message: `任务创建失败${err}`,
                  duration: 2000
                })
              })
          }
        })
        .catch(() => { })
    },
    // 删除图片
    removeImg(imgId) {
      this.imagesList.splice(imgId, 1)
    },
    // 删除图片
    removeImg2(imgId) {
      this.priceImagesList.splice(imgId, 1)
    },
    // 展示大图
    showBigImg(imgUrl) {
      this.dialogImageUrl = imgUrl
      this.dialogVisible = true
    },
    // 拖拽图片
    imgDragOver(e, index) {
      this.imgTarget = index
      e.preventDefault()
    },
    // 拖拽图片
    imgDragEnd(e, index) {
      [this.imagesList[index], this.imagesList[this.imgTarget]] = [
        this.imagesList[this.imgTarget],
        this.imagesList[index]
      ]
      this.$forceUpdate()
      e.preventDefault()
    },
    // 选择图片|视频
    choseMedia() {
      const fileObj = this.$refs.sendCircleUpload.files // 文件对象
      if (!fileObj || fileObj.length === 0) return
      //   const loading = this.$loading({
      //     lock: true,
      //     text: '文件上传中',
      //     spinner: 'el-icon-loading',
      //     background: 'rgba(0, 0, 0, 0.7)'
      //   })
      for (const fo of fileObj) {
        const formdata = new FormData() // 上传
        formdata.append('myfile', fo)

        fileUpload(formdata)
          .then((res) => {
            console.log("1",res)
            if (res.bizCode === 0 && res.data) {
              if (this.circleType === 'picture') {
                if (this.imagesList.length < 9) {
                  this.imagesList.push(res.data?.url)
                }
              } else {
                this.videoList.push(res.data?.url)
              }
            }
          })
          .catch((err) => {
            console.log('文件上传失败', err)
            this.$message({
              message: '文件上传失败:' + err,
              type: 'error',
              duration: 2000
            })
            // loading.close()
          })
      }
    },
    // 选择图片|视频
    choseMedia2() {
      const fileObj = this.$refs.sendCircleUpload2.files // 文件对象
      if (!fileObj || fileObj.length === 0) return
      for (const fo of fileObj) {
        const formdata = new FormData() // 上传
        formdata.append('myfile', fo)
        fileUpload(formdata)
          .then((res) => {
            console.log("2",res)
            if (res.bizCode === 0 && res.data) {
              this.priceImagesList.push(res.data?.url)
            }
          })
          .catch((err) => {
            console.log('文件上传失败', err)
            this.$message({
              message: '文件上传失败:' + err,
              type: 'error',
              duration: 2000
            })
            // loading.close()
          })
      }
    },
    // 全选/全不选
    choseAllWechats() {
      if (this.allChoseRadio) {
        for (const wechat of this.wechatsUnchose) {
          this.wechatsChose.push(wechat)
        }
      } else {
        this.wechatsChose = []
      }
    },
    // 全选/全不选
    choseAllWechats2() {
      if (this.allChoseRadio2) {
        for (const wechat of this.wechats2send) {
          this.wechatsChose2.push(wechat)
        }
      } else {
        this.wechatsChose2 = []
      }
    },
    // 单选
    choseWechat(wechat) {
      const wid = this.wechatsChoseMap[wechat.wechatid]
      if (wid) {
        // 取消选中
        this.wechatsChose = this.wechatsChose.filter((x) => {
          return x.wechatid !== wechat.wechatid
        })
        this.allChoseRadio = false
      } else {
        // 选中
        this.wechatsChose.push(wechat)
        if (this.wechatsChose.length === this.wechatsUnchose.length) {
          this.allChoseRadio = true
        }
      }
    },
    // 单选
    choseWechat2(wechat) {
      const wid = this.wechatsChoseMap2[wechat.wechatid]
      if (wid) {
        // 取消选中
        this.wechatsChose2 = this.wechatsChose2.filter((x) => {
          return x.wechatid !== wechat.wechatid
        })
        this.allChoseRadio2 = false
      } else {
        // 选中
        this.wechatsChose2.push(wechat)
        if (this.wechatsChose2.length === this.wechats2send.length) {
          this.allChoseRadio2 = true
        }
      }
    },
    // 添加到已选账号
    add2Send() {
      this.wechats2send = this.wechats2send.concat(this.wechatsChose)
      const wsm = {}
      for (const w2s of this.wechats2send) {
        wsm[w2s.wechatid] = true
      }
      this.wechatsUnchose = this.wechatsList.filter((x) => {
        return !wsm[x.wechatid]
      })
      this.wechatsChose = []
      this.allChoseRadio = false
    },
    // 移除已选账号
    remove2send() {
      this.wechatsUnchose = this.wechatsUnchose.concat(this.wechatsChose2)
      const wsm = {}
      for (const w2s of this.wechatsUnchose) {
        wsm[w2s.wechatid] = true
      }
      this.wechats2send = this.wechatsList.filter((x) => {
        return !wsm[x.wechatid]
      })
      this.wechatsChose2 = []
      this.allChoseRadio2 = false
    },
    // 根据分组选微信
    groupChangeHandle(groups) {
      // 分组对应的微信
      const groupsWechats = this.wechatsList.filter((x) => {
        return groups.indexOf(x.groupid) >= 0
      })
      const gwm = {}
      groupsWechats.forEach((element) => {
        gwm[element.wechatid] = true
      })
      // 分组中的微信合并到已选账号
      this.wechats2send = uniqueArryList(this.wechats2send.concat(groupsWechats), 'wechatid')
      // 从账号列表中移除分组中的微信
      this.wechatsUnchose = this.wechatsUnchose.filter((x) => {
        return !gwm[x.wechatid]
      })
    },
    // 根据分组移除微信
    removeGroup(tag) {
      // 重新计算未选微信的数据
      const recoverData = this.wechats2send.filter((x) => {
        return x.groupid === tag
      })
      this.wechatsUnchose = this.wechatsUnchose.concat(recoverData)
      // 删除已选微信中的数据
      this.wechats2send = this.wechats2send.filter((x) => {
        return x.groupid !== tag
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.send-circle {
  // height: calc(100vh - 84px);
  height: 100%;
  width: 100%;
  display: flex;

  .circle-content {
    width: 50%;
    display: flex;
    flex-direction: column;

    .set-content {
      flex: 1 1 auto;
      overflow: auto;

      .send-circle-time {
        display: flex;
        align-items: center;
        padding: 10px;
      }

      .send-circle-item {
        display: flex;
        align-items: center;
        padding: 15px;

        .circle-item-tip {
          width: 60px;
          min-width: 60px;
          margin-right: 20px;
          // text-align: right;
        }

        .media-list {
          // padding: 5px;
          display: flex;
          flex-wrap: wrap;

          .img-item {
            margin: 5px;
            position: relative;
            cursor: pointer;

            &:hover {
              .img-url {
                filter: contrast(0.6);
              }

              .img-delete {
                display: block;
              }
            }

            .img-url {
              width: 100px;
              height: 100px;
              object-fit: cover;
            }

            .img-delete {
              display: none;
              font-size: 20px;
              color: #fff;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }

          .upload-box {
            width: 100px;
            height: 100px;
            font-size: 25px;
            display: flex;
            margin: 5px;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #dcdfe6;
            border: 1px solid #dcdfe6;
          }
        }

        .sent-time-content {
          display: flex;
          align-items: center;
        }

        .link-content {
          display: flex;
          flex: 1 1 auto;
          justify-content: space-between;

          .link-content-item {
            width: 45%;
            display: flex;
            flex-direction: column;

            .preview-box {
              align-items: center;
              display: flex;
            }

            .link-title {
              line-height: 20px;
            }
          }
        }
      }
    }

    .create-btn {
      display: flex;
      justify-content: center;
    }
  }

  .chose-wechat {
    display: flex;
    flex-direction: column;
    flex: 1 1 auto;

    .chose-wechat-item {
      padding: 20px;
      width: 100%;
    }

    .wechats-list {
      padding: 0 20px;
      flex: 1 1 auto;
      overflow: hidden;
      display: flex;

      .wechats-unchose {
        width: 40%;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .wechats-unchose-title {
          height: 40px;
          line-height: 40px;
          padding: 0 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border: solid #c8cbd3 1px;
        }

        .wechats-unchose-list {
          flex: 1 1 auto;
          display: flex;
          overflow: auto;
          flex-direction: column;
          border: solid #c8cbd3 1px;

          .wechats-unchose-item {
            display: flex;
            align-items: center;
            padding: 0 20px;
            height: 40px;
            line-height: 40px;
          }
        }
      }

      .chose-wechat-btns {
        flex: 1 1 auto;
        padding: 20px;
        max-width: 200px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
      }
    }
  }
}

.date-picker-container {
  display: inline-block;
  position: relative;
}

.btns {
  display: flex;

  button {
    margin: 5px;
    padding: 5px;
    box-shadow: 0px;
    border: 1px solid #ccc;
    background-color: #fff;
    color: #666;
  }
}
</style>
